UIGiftHero = Class("UIGiftHero", UIComponentBase)

function UIGiftHero:OnCreate( _id, _parent)
    self.activeId = _id
    self.parent = _parent

    self.ctrl_tip_type = self:GetController("tipType")
    self.draw_wrapper = GoWrapper.New()
    self.lihui = self:GetChild("lihui")
    self.lihui2 = self:GetChild("lihui2")
    self.txt_banner = self:GetChild("bannerText")
    self.title = self:GetChild("title")
    self.hero_list = self:GetChild("HeroList")
    self:SetDynamicList(self.hero_list, self.UpdateHeroItem, nil, true)
    self.btn_help = self:GetChild("help")

    self.btn_help.onClick:Clear()
    self:RegisterOnClick(self.btn_help, self.ClickHelp)
end

-- 更新列表数据
function UIGiftHero:UpdateHeroItem(index, item_obj)
    local ctr_progress_up = item_obj:GetController("progressUp")
    local ctr_progress_down = item_obj:GetController("progressDown")
    local ctr_state1 = item_obj:GetController("state1")
    local ctr_state2 = item_obj:GetController("state2")

    local hero_item = item_obj:GetChild("Hero")
    local list_free = item_obj:GetChild("itemListFree") 
    local list_money = item_obj:GetChild("itemListMoney") 

    local btn_get_free = item_obj:GetChild("getFree") 
    local btn_get_buy = item_obj:GetChild("getBuy") 
    local txt_buy_tips = item_obj:GetChild("Text")
    txt_buy_tips.text = ""

    btn_get_free.onClick:Clear()
    btn_get_buy.onClick:Clear()
    ctr_progress_up:SetSelectedIndex(0)
    ctr_progress_down:SetSelectedIndex(0)
    list_free.numItems = 0
    list_money.numItems = 0 
    local ctr_progress_bg = item_obj:GetController("isshowup")
    if index == 1  then
        ctr_progress_bg:SetSelectedIndex(0)
    else
        ctr_progress_bg:SetSelectedIndex(1)
    end
    local item_data = self.severData and self.severData.items[index]
    -- print("--------------------", index, table.tostring(item_data) )
    if item_data ~= nil then 
        self:RefreshHeroItem(hero_item, item_data.hero)
        logicMgr.CostManager.RefreshItemList(list_free, item_data.base_reward)
        logicMgr.CostManager.RefreshItemList(list_money, item_data.advanced_reward )
        if item_data.buy_price > 0 then
            btn_get_buy.title = "￥"..item_data.buy_price
        else
            btn_get_buy.title = "免费"
        end
        --  
        local can_buy = self:CanBuy( item_data.hero ) 
        if can_buy then
            if index ~= 1 then
                ctr_progress_up:SetSelectedIndex(1)
            end 
            local next_item_data = self.severData and self.severData.items[index+1]
            if next_item_data ~= nil then
                local next_can_buy = self:CanBuy( next_item_data.hero ) 
                if next_can_buy then
                    ctr_progress_down:SetSelectedIndex(1) 
                end
            end
            
            if item_data.get_free_count > 0 then
                ctr_state1:SetSelectedIndex(2)
            else
                ctr_state1:SetSelectedIndex(1)
                self:RegisterOnClick(btn_get_free, function()
                    self:GetFreeReward( index )
                end)
            end
            if item_data.get_buy_count >= item_data.buy_count then
                ctr_state2:SetSelectedIndex(2)
            else
                txt_buy_tips.text = string.format(getLanguage("ActivityDesc1006"), item_data.buy_count-item_data.get_buy_count, item_data.buy_count)
                ctr_state2:SetSelectedIndex(1) 
                self:RegisterOnClick(btn_get_buy, function()
                    self:BuyAdvancedReward( index )
                end)
            end 
        else
            txt_buy_tips.text = string.format(getLanguage("ActivityDesc1006"), item_data.buy_count, item_data.buy_count)
            ctr_state1:SetSelectedIndex(0)
            ctr_state2:SetSelectedIndex(0)
            local quality = logicMgr.HeroManager.starToQuality(item_data.hero and item_data.hero[2] or 1)
            self:RegisterOnClick(btn_get_buy, function() 
                if self.severData ~= nil then
                    local dis_time =  self.severData.endTime - Config.serverTime/1000
                    if dis_time <= 0 then
                        UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"))
                        return
                    end
                end
                UISysTips.AddMsg(string.format(getLanguage("storedesc1090102"), getLanguage("Sys_Quality"..quality) ) )
            end)
            self:RegisterOnClick(btn_get_free, function()
                if self.severData ~= nil then
                    local dis_time =  self.severData.endTime - Config.serverTime/1000
                    if dis_time <= 0 then
                        UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"))
                        return
                    end
                end
                UISysTips.AddMsg(string.format(getLanguage("storedesc1090101"), getLanguage("Sys_Quality"..quality) ) )
            end)
        end

        -- local next_item_data = self.severData and self.severData.items[index+1]
        -- local next_can_buy = self:CanBuy(next_item_data and next_item_data.hero)
        -- if next_can_buy  then
        --     ctr_progress_down:SetSelectedIndex(0) 
        -- end
    end
end

function UIGiftHero:CanBuy( hero_data )  
    if hero_data ~= nil then
        local star = HeroManager.GetHeroStarByPartnerModelId(hero_data[1])
        if star >= tonumber(hero_data[2]) then
            return true
        end
    end
    return false
end
function UIGiftHero:GetFreeReward( index )
    if self.severData ~= nil then
        local dis_time =  self.severData.endTime - Config.serverTime/1000
        if dis_time <= 0 then
            UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"))
            return
        end
    end
    local item_data = self.severData and self.severData.items[index]
    if item_data ~= nil then
        local data = {}
        table.insert(data, item_data.item_id)
        logicMgr.CostManager.getRewardById(self.activeId, data, nil, self)
    else
        error("UIGiftHero:GetFreeReward 数据错误")
    end
end

function UIGiftHero:BuyAdvancedReward( index )
    if self.severData ~= nil then
        local dis_time =  self.severData.endTime - Config.serverTime/1000
        if dis_time <= 0 then
            UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"))
            return
        end
    end

    local item_data = self.severData and self.severData.items[index]
    if item_data ~= nil then
        logicMgr.CostManager.getRewardByIdAndIndex(self.activeId, item_data.item_id, item_data.product_id, 1, item_data.buy_price, self.onBuySuccess, self)
    else
        error("UIGiftHero:BuyAdvancedReward 数据错误")
    end
end
function UIGiftHero:onBuySuccess( index )
end

function UIGiftHero:RefreshHeroItem( obj, data)
    local hero_star = data and data[2] or 0
    local hero_model_id = data and data[1] or 0
    local hero_cfg = HeroManager.GetHeroConfigbyModelId(hero_model_id)
    local img_quality = obj:GetChild("quality")
    local img_frame = obj:GetChild("frame")
    local img_icon = obj:GetChild("icon")
    local txt_num = obj:GetChild("num")
    txt_num.visible = false
 
    local quality = logicMgr.HeroManager.starToQuality(hero_star) --hero_cfg.f_HeroInitialStar)
    if quality == nil or quality == 0 then
        quality = 1
    elseif quality > #Config.IconQuality then
        quality = #Config.IconQuality
    end
    img_frame.url = "ui://ICONAtlas/" .. Config.IconFrame[quality]
    img_quality.url = "ui://ICONAtlas/" .. Config.IconQuality[quality]
    -- txt_num.text = tostring(hero_level)
    img_icon.url = "ui://ICONAtlas/" .. hero_cfg.f_HeroIcon
end 

-- 点击帮助
function UIGiftHero:ClickHelp()
    if self.modelTableData ~= nil and next(self.modelTableData) ~= nil then
        local txts = {} 
        txts["title"] = self.modelTableData.f_ExplainTitle
        txts["des"] = self.modelTableData.f_ExplainText
        showUI(PanelNames.CommonTips, txts)
    end
end

function UIGiftHero:Refresh() -- 刷新数据
    self.severData, self.modelTableData = logicMgr.CostManager.getCostData(self.activeId) 
    self.hero_list.numItems = self.severData and self.severData.items and #self.severData.items or 0
    self.title.text = getLanguage(self.modelTableData.f_Title)
     
    if self.modelTableData.f_BannerTipsType == 0 then
        self.ctrl_tip_type:SetSelectedIndex(0)
    elseif self.modelTableData.f_BannerTipsType == 1 then
        self.ctrl_tip_type:SetSelectedIndex(1) 
        local dis_time =  self.severData.endTime - Config.serverTime/1000
        if dis_time > 0 then
            self.txt_banner.text = string.format(getLanguage(self.modelTableData.f_BannerTips), getTimeStr(dis_time))
            if self.activity_time_id ~= nil then
                utimer.remove(self.activity_time_id)
                self.activity_time_id = nil 
                self.banner_tips_str = nil
            end
            self.activity_time_id = utimer.timeCall(function() 
                dis_time = dis_time -1 
                if self.txt_banner then
                    local tips_str = string.format(getLanguage(self.modelTableData.f_BannerTips), getTimeStr(dis_time))
                    if self.banner_tips_str == nil or self.banner_tips_str ~= tips_str then
                        self.txt_banner.text =  tips_str
                        self.banner_tips_str = tips_str
                    end
                end
                if dis_time <= 0 then 
                    if self.txt_banner then
                        self.txt_banner.text = getLanguage("Sys_ActivityEnd")
                    end
                    utimer.remove(self.activity_time_id)
                    self.activity_time_id = nil 
                end
            end, 1000, dis_time) 
        else
            self.txt_banner.text = getLanguage("Sys_ActivityEnd")
        end
        
    elseif self.modelTableData.f_BannerTipsType == 2 then
        self.ctrl_tip_type:SetSelectedIndex(1) 
        local dis_time =  self.severData.endTime - Config.serverTime/1000
        self.txt_banner.text = string.format(getLanguage(self.modelTableData.f_BannerTips), getTimeStr(dis_time))
    end
    self.parent:updateCostShowByTableOrJson(self.modelTableData.f_ResourceShow);
    if self.lihui ~= nil then
        logicMgr.CostManager.updateLiHui(self, self.draw_wrapper, self.lihui, self.lihui2, self.modelTableData.f_HeroSpine)
    end
end
 
-- 卸载
function UIGiftHero:OnDestroy() 
    if self.activity_time_id ~= nil then
        utimer.remove(self.activity_time_id)
        self.activity_time_id = nil 
    end
    self.id = nil
    self.parent = nil
    self.ctrl_tip_type = nil
    
    -- if self.draw_wrapper ~= nil then
    --     destroyImmediate(self.draw_wrapper)
        self.draw_wrapper = nil 
        self.lihui = nil
    -- end
    self.txt_banner = nil
    self.title = nil
    self.hero_list = nil
    self.btn_help = nil
  
    self.severData = nil
    self.modelTableData = nil
    self.banner_tips_str = nil
    if self._package and UIPackage.GetById(self._package) then
        UIPackage.RemovePackage(self._package)
    end
end